//
//  RAPStatusesListViewModel.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 12/31/15.
//  Copyright © 2015 RendezvousAuParadis. All rights reserved.
//

import UIKit
import SDWebImage

enum RAPLoadMoreStatuses {
    case New
    case Past
}

class RAPStatusesListViewModel: NSObject {
    /**
    单例属性
    */
    static let sharedViewModel = RAPStatusesListViewModel()
    
    var lastestStatusesCount: Int?
    
    var statusArray: [RAPStatusCellViewModel]?
    
    func loadStatuses(statusID: Int64 = 0, kind: RAPLoadMoreStatuses = .New, completion:(isSuccess: Bool)->()) {
        // since 最新
        // max 过去
        
        let since_id = kind == .New ? statusID : 0
        let max_id = kind == .Past ? (statusID < 0 ? 0 : statusID) : 0 // 防止 since_id出现-1
        
        // since_id不会出现为-1的情况
        
        RAPAFNHTTPRequestTool.sharedTool.fetchStatuses(max_id: max_id, since_id: since_id) {(responseObject, error) -> () in
            if error != nil {
                completion(isSuccess: false)
                return
            }
            let tmpArr = (responseObject as! [String : AnyObject])["statuses"] as! [[String : AnyObject]]
            
            var modelArr = [RAPStatusCellViewModel]()
            // 字段转模型
            for dict in tmpArr {
                let statusModel = RAPStatusModel(dict: dict)
                // 将 RAPStatusModel 交给 RAPStatusCellViewModel（视图模型）
                // 然后再将视图模型装入数组
                let statusCellViewModel = RAPStatusCellViewModel(statusModel: statusModel)
                modelArr.append(statusCellViewModel)
            }
            
            if self.statusArray == nil {
                self.statusArray = modelArr
                
            } else {
                if kind == .New { // 新的微博数据，加载数组开头
                    self.statusArray?.insertContentsOf(modelArr, at: 0)
                } else { // 以往的微博数据，记载数组末尾
                    self.statusArray! += modelArr
                    
                }
            }
            self.lastestStatusesCount = modelArr.count
            
            // 与缓存配图的第一张图片
            self.precacheSingleStatusPicture(completion)
        }
    }
    
    private func precacheSingleStatusPicture(completion:(isSuccess: Bool)->()) {
        // 创建任务分组和队列
        let group = dispatch_group_create()
        let queue = dispatch_get_global_queue(0, 0)
        
        // 遍历微博模型数组
        
        for statusCellViewModel in statusArray! {
            
            
            if statusCellViewModel.statusPictureModelArr?.count == 1 {
                downloadImageWithURL((statusCellViewModel.statusPictureModelArr?.first?.thumbnail_pic)!, GCD_group: group, GCD_queue: queue)
            } else {
                continue
            }
            
        }
        
        dispatch_group_notify(group, queue) { () -> Void in
//            RAPLog("图片下载完毕")
            // 数据请求并缓存成功
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completion(isSuccess: true)
            })
        }
            
        
    }
    
    private func downloadImageWithURL(urlString: String, GCD_group: dispatch_group_t, GCD_queue: dispatch_queue_t) {
        let url = NSURL(string: urlString)
        let mgr = SDWebImageManager.sharedManager()
        // 入组
        dispatch_group_enter(GCD_group)
        
        dispatch_async(GCD_queue, { () -> Void in
            mgr.downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                // 将下载好的图片存入缓存
                mgr.saveImageToCache(image, forURL: url)
                // 出组
                dispatch_group_leave(GCD_group)
            })
        })
        

    }
    
}
